﻿using System;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace AppToolkit.WPF.Tests.Controls
{
    public class BitmapHelper
    {
        /// <summary>
        /// Creates a bitmap showing random noize.
        /// </summary>
        /// <returns><see cref="BitmapSource"/></returns>
        public static BitmapSource CreateTestImage(int width = 200, int height=200)
        {
            // Define parameters used to create the BitmapSource.
            var pf = PixelFormats.Bgr32;
            
            int       rawStride       = (width * pf.BitsPerPixel + 7) / 8;
            var       rawImage        = new byte[rawStride * height];

            // Initialize the image with data.
            var value = new Random();
            value.NextBytes(rawImage);

            // Create a BitmapSource.
            var bitmap = BitmapSource.Create(width, height,
                                             96, 96, pf, null,
                                             rawImage, rawStride);

            return bitmap;
        }

        /// <summary>
        /// Creates a <see cref="BitmapSource"/> add sets the UriSource accordingly.
        /// </summary>
        /// <param name="uriString">e.g. @"Controls/TestImage.png"</param>
        /// <returns></returns>
        public BitmapSource LoadTestImage(string uriString)
        {
            // Create source.
            var bi = new BitmapImage();
            // BitmapImage.UriSource must be in a BeginInit/EndInit block.
            bi.BeginInit();
            bi.UriSource = new Uri(uriString, UriKind.RelativeOrAbsolute);
            bi.EndInit();
            return bi;
        }
    }
}